package com.jjh.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jjh.consts.Result;
import com.jjh.controller.FileController;
import com.jjh.controller.UserController;
import com.jjh.mapper.UserMapper;
import com.jjh.pojo.User;
import com.jjh.service.UserService;
import com.jjh.utils.MD5Util;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.*;


@Service
@Slf4j
public class UserServiceImpl implements UserService {


    @Resource
    private UserMapper userMapper;
    @Value("${img.userImgPath}")
    private String userImgPath;


    @Override
    public User getByUserName(String username) {
        return userMapper.getByUserName(username);
    }

    @Override
    public User getById() {
        return null;
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    @Transactional
    @Override
    public Result insertOne(User user) {
        try {
            int row = userMapper.insert(user);
            if(row>0){
                return Result.ok("添加成功");
            }else {
                return Result.error("添加失败");
            }
        } catch (Exception e) {
             return  Result.error("未知错误:"+e.getMessage());
        }
    }

    @Override
    public boolean updateById(User user) {
        return false;
    }

    @Override
    public boolean deleteById(Integer id) {
        return false;
    }

    @Override
    public Result page(Integer page,Integer size,Map<String, Object> map) {

        PageHelper.startPage(page,size);
        List<User> users = getByCondition(map);
        PageInfo<User> pageInfo = new PageInfo<>(users);
        return Result.ok(pageInfo);
    }

    @Override
    public List<User> getByCondition(Map<String, Object> conditions) {
        return userMapper.getByCondition(conditions);
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    @Override
    public Result addUser(User user) {
        //校验
        List<String> validate = validate(user,1);
        if(validate.get(0).equals("false")){
            return Result.error(validate.get(1));
        }

        //都没事了，然后进行加密
        String encode = MD5Util.encode(user.getPassword());
        user.setPassword(encode);
        //添加到数据库中去
        int row = userMapper.insert(user);
        if(row>0){
            return Result.ok("添加成功");
        }else{
            log.error("添加用户失败:{}",user);
            return Result.error("添加失败!");
        }
    }

    @Override
    public User getByName(String name) {
        return userMapper.getByName(name);
    }

    /**
     * 修改用户状态
     * @param status
     * @return
     */
    @Override
    public Result changeStatus(Integer id,Integer status) {
        if(status == 1){
            userMapper.updateStatus("启用",id, LocalDateTime.now());
        }else {
            userMapper.updateStatus("禁用",id,LocalDateTime.now());
        }
        return Result.ok("状态修改成功");
    }

    /**
     * 修改用户
     * @param user
     * @return
     */
    @Override
    public Result updateUser(User user) {
        List<String> validate = validate(user,2);
        if(validate.get(0).equals("false")){
            return Result.error(validate.get(1));
        }
        user.setPassword(MD5Util.encode(user.getPassword()));
        //校验通过可以修改
        int row = userMapper.updateByPrimaryKey(user);
        if(row>0){
            return Result.ok("修改成功");
        }else {
            log.error("修改用户失败:{}",user);
            return Result.error("修改失败!");
        }
    }

    /**
     * 根据ids批量删除
     * @param ids id数组
     * @return
     */
    @Transactional
    @Override
    public Result deleteByIds(List<Integer> ids) {
        //先查询userimg
         List<User> users = userMapper.getByIds(ids);
        for (User user : users) {
            String userImg = user.getUserImg();
            //删除图片
            FileController.deleteImg(userImg,userImgPath);
        }
        //然后再批量删除用户
        userMapper.deleteByIds(ids);
        return Result.ok("删除成功");
    }

    /**
     * 校验用户
     * @param user
     * @return
     */
    public  List<String> validate(User user,Integer IorU){
         List<String> resList = new ArrayList<>();
         resList.add("false");
        //获取username
        String username = user.getUsername();
        if(ObjectUtils.isEmpty(username)||"".equals(username)){
            resList.add("用户名不能为空");
            return resList;
        }
        String password =user.getPassword();
        if(ObjectUtils.isEmpty(password)||"".equals(password)){
            resList.add("密码不能为空");
            return resList;
        }
        String userImg = user.getUserImg();
        if(ObjectUtils.isEmpty(userImg)||"".equals(userImg)){
            resList.add("图片不能为空");
            return resList;
        }
        String name = user.getName();
        if(ObjectUtils.isEmpty(name)||"".equals(name)){
            resList.add("姓名不能为空");
            return resList;
        }
        String phone = user.getPhone();
        if(ObjectUtils.isEmpty(phone)||"".equals(phone)){
            resList.add("手机号不能为空");
            return resList;
        }
        String status = user.getStatus();
        if(!"启用".equals(status) && !"禁用".equals(status)){
            resList.add("状态非法");
            return resList;
        }
        //添加走这条逻辑
        if(IorU == 1){
            //都合法了，下面查询看看有没有username重复的
            User user1 = userMapper.getByUserName(username);
            if(!ObjectUtils.isEmpty(user1)){
                resList.add("该用户已经存在");
                return resList;
            }
            //在看看name有没有重名的
            User user2 = this.getByName(name);
            if(!ObjectUtils.isEmpty(user2)){
                resList.add("该姓名的用户已经存在");
                return resList;
            }
            resList.set(0,"true");
            return resList;
        }else{
            //修改走这条逻辑
            //都合法了，下面查询看看有没有username重复的
            User user1 = userMapper.getByUserName(username);
            User user2 = userMapper.getByName(name);
            if(!ObjectUtils.isEmpty(user1)&&!ObjectUtils.isEmpty(user2)
               && Objects.equals(user.getId(), user1.getId())
               && Objects.equals(user.getId(), user2.getId())
            ){
                resList.set(0,"true");
                return resList;
            }else{
                resList.add("该用户是其他用户，不能修改");
                return resList;
            }
        }

//        //上面的都没错，则可以返回true
//        resList.set(0,"true");
//        return resList;
    }
}
